package com.cloud.serviceverificationcode.compent;

import com.cloud.internalcommon.dto.ResponseResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
public class ExceptionAdvice {


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseResult<?> methodNotValidException(MethodArgumentNotValidException e){
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        Map<String,String> errorMap = new HashMap<>();
        for (FieldError fieldError : fieldErrors) {
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        }
        return ResponseResult.fail(errorMap);
    }
}
